package 单例模式练习;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-05
 * Time: 19:03
 */
class SingleTonLazy{
    //在类加载时并没有创建实例对象 private修饰,类外无法直接拿到 volatile避免指令重排序和内存可见性带来问题
    private static volatile SingleTonLazy singleTonLazy  = null;
    //构造方法也是用private修饰,无法在创建出实例对象
    private SingleTonLazy() {
    }

    //只有在调用getSingleTonLazy时才会创建对象 static方法,通过类名来访问
    public static SingleTonLazy getSingleTonLazy(){
        if(singleTonLazy == null){
            synchronized (SingleTonLazy.class){//注意这里锁的对象不能是this
                if (singleTonLazy == null){
                    singleTonLazy = new SingleTonLazy();
                }
                return singleTonLazy;
            }
        }
        return singleTonLazy;


    }

}
public class demo2 {
    public static void main(String[] args) {
        SingleTonLazy.getSingleTonLazy();
    }
}
